#include "UdpServer.hpp"
#include "Log.hpp"

int main(int args, char* argv[])
{
    if(args != 3)
    {
        std::cout << "you should enter : target ip and target port" << std::endl;
        exit(2);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);//将字符串转为整型

    //1.创建socket
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    
    //2.本地服务器不需要显示bind
    //将目标服务器的内容保存到strcut sockaddr_in 结构体中
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);//将系统默认字节序转为网络字节序
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());//将c风格的点分十进制ip 转为 四字节风格的ip

    while(true)
    {
        std::string input;
        std::cout << "请输入：" << std::endl;
        std::getline(std::cin,input);
        int n = sendto(sockfd,input.c_str(),input.size(),0,(sockaddr*)&server,sizeof(server));//本地客户端的数据 发送到目标IP和端口号中
        if(n < 0)
        {
            LOG(LogLevel::DEBUG) << "sendto error  " ;
            exit(1);
        }

        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t s = recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(sockaddr*)&peer,&len);//本地客户端接收远端服务器发送的消息，远端的数据 ip 端口 分别保存到buffer peer中
        if(s>0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }

    }

    return 0;
}
